<!DOCTYPE html>
<html>

<head>
    <!-- 文档元数据 -->
    <meta charset="utf-8"> <!-- 设置字符编码为UTF-8 -->
    <title>题库</title> <!-- 页面标题 -->

    <!-- 内部样式表 -->
    <style>
        /* 容器样式 - 使用45度角的重复线性渐变背景 */
        .container {
            background: repeating-linear-gradient(45deg,
                    rgba(255, 99, 132, 0.1),
                    rgba(255, 99, 132, 0.1) 10px,
                    rgba(54, 162, 235, 0.1) 10px,
                    rgba(54, 162, 235, 0.1) 20px);
            width: 600px;
            /* 固定宽度 */
            padding: 5px;
            /* 内边距 */
            margin: auto;
            /* 水平居中 */
            margin-bottom: auto;
            /* 底部外边距自动 */
            border: 1px solid rgba(128, 128, 128, 0.3);
            /* 半透明灰色边框 */
        }

        /* 段落基础样式 */
        p {
            padding: 3px;
            /* 内边距 */
            margin: 2px;
            /* 外边距 */
            font-size: medium;
            /* 中等字体大小 */
        }

        /* 题目样式 */
        .subject {
            font-size: large;
            /* 大号字体 */
            background-color: GoldenRod;
            /* 金黄色背景 */
            color: white;
            /* 白色文字 */
        }

        /* 选项样式 */
        .option {
            font-size: medium;
            /* 中等字体大小 */
        }

        /* 正确答案样式 - 虚线边框 */
        .correct_answer {
            border: 1px dashed GoldenRod;
        }

        #info-panel {
            position: fixed;
            top: 20px;
            right: 20px;
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 15px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
            z-index: 1000;
            text-align: right;
            opacity: 0.3;
        }

        .time-display {
            font-size: 18px;
            margin-bottom: 10px;
            opacity: 0.7;
        }

        .load-time {
            font-size: 14px;
            color: #ccc;
            opacity: 0.7;
        }
    </style>
</head>

<body>
    <!-- 主容器元素 -->
    <div id="container" class="container"></div>
    <!-- 固定位置显示时间和加载时长 -->>
    <div id="info-panel">
        <div class="time-display" id="current-time">加载中...</div>
        <div class="load-time">页面加载时长: <span id="load-time">0</span> 秒</div>
    </div>
</body>

<!-- 第一个脚本：滚动位置保存与恢复 -->
<script>
    const container = document.getElementById('container');
    container.innerHTML = ""; // 清空容器内容

    // 保存滚动位置到本地存储
    function saveScrollPosition() {
        const position = window.scrollY || document.documentElement.scrollTop;
        localStorage.setItem('savedScrollPos', position);
    }

    // 从本地存储恢复滚动位置
    function restoreScrollPosition() {
        const savedPos = localStorage.getItem('savedScrollPos');
        if (savedPos !== null) {
            window.scrollTo(0, Number(savedPos));
        }
    }

    // 添加事件监听器
    window.addEventListener('scroll', saveScrollPosition); // 滚动时保存位置
    window.addEventListener('load', restoreScrollPosition); // 加载时恢复位置

    // 生成随机颜色（带透明度）
    function getRandomColor(alpha = true) {
        const r = Math.floor(Math.random() * 150 + 50); // 红色分量 (50-200)
        const g = Math.floor(Math.random() * 150 + 50); // 绿色分量 (50-200)
        const b = Math.floor(Math.random() * 150 + 50); // 蓝色分量 (50-200)
        const a = alpha ? (Math.random() * 0.1).toFixed(2) : 0.1; // 透明度 (0-0.1)
        return `rgba(${r}, ${g}, ${b}, ${a})`;
    }

    // 更新页面背景渐变
    function updateGradient() {
        const randomAngle = Math.floor(Math.random() * 360) + 'deg'; // 随机角度
        const stripeWidth = Math.floor(Math.random() * 25) + 5; // 条纹宽度 (5-30px)
        const gapWidth = Math.floor(Math.random() * 25) + 5; // 间隙宽度 (5-30px)
        const totalPeriod = stripeWidth + gapWidth; // 总周期

        // 创建重复线性渐变
        const gradient = `repeating-linear-gradient(
        ${randomAngle},
        ${getRandomColor()},
        ${getRandomColor()} ${stripeWidth}px,
        ${getRandomColor()},
        ${getRandomColor()} ${totalPeriod}px
      )`;
        document.body.style.background = gradient; // 应用渐变
    }

    // 初始化并设置定时器每30秒更新一次渐变
    updateGradient();
    setInterval(updateGradient, 30000);
</script>

<script>
    // 记录页面加载开始时间
    const pageLoadStartTime = Date.now();

    // 更新当前时间函数
    function updateCurrentTime() {
        const now = new Date();
        const timeElement = document.getElementById('current-time');

        // 格式化时间为 HH:MM:SS
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');

        timeElement.textContent = `当前时间: ${hours}:${minutes}:${seconds}`;
    }

    // 更新加载时长函数
    function updateLoadTime() {
        const currentTime = Date.now();
        const elapsedSeconds = Math.floor((currentTime - pageLoadStartTime) / 1000);
        document.getElementById('load-time').textContent = elapsedSeconds;
    }

    // 页面加载完成后初始化
    window.onload = function () {
        // 立即更新一次时间和加载时长
        updateCurrentTime();
        updateLoadTime();

        // 设置定时器每秒更新一次时间
        setInterval(updateCurrentTime, 1000);

        // 设置定时器每秒更新一次加载时长
        setInterval(updateLoadTime, 1000);
    };
</script>

<!-- 第二个脚本：题库渲染逻辑 -->
<script>
    // 颜色名称数组
    const colorName = [
        "AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue",
        "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson",
        "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "DarkOrange",
        "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue",
        "DimGray", "DodgerBlue", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod",
        "Gray", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender",
        "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGreen", "LightPink",
        "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta",
        "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed",
        "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange",
        "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink",
        "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen",
        "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "Snow", "SpringGreen", "SteelBlue", "Tan",
        "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "WhiteSmoke", "Yellow", "YellowGreen"
    ];

    // 从颜色名称数组中随机获取一个颜色名
    function getRandomColorName() {
        return colorName[Math.floor(Math.random() * colorName.length)];
    }

    // 元素添加工具对象
    const appendElement = {
        // 主渲染函数 - 处理题库数据
        main(baseDict) {
            // 遍历题库数据的第一层
            Object.entries(baseDict).forEach(item => {
                document.title = item[0]; // 设置页面标题
                this.addTitle(item[0], container, "h1"); // 添加一级标题

                // 遍历题库数据的第二层
                Object.entries(item[1]).forEach(e => {
                    this.addTitle(e[0], container, "h2"); // 添加二级标题

                    // 遍历题库数据的第三层
                    Object.entries(e[1]).forEach(f => {
                        this.addTitle(f[0], container, "h3"); // 添加三级标题

                        // 遍历具体题目
                        f[1].forEach((g, i) => {
                            this.subject(g.subject) // 添加题目
                            this.option(g.option, g.answer) // 添加选项
                        })
                    })
                })
            });

            // 为所有题目元素设置随机背景色
            const bgColor = getRandomColorName();
            const subjects = document.querySelectorAll('.subject');
            subjects.forEach(element => {
                element.style.backgroundColor = bgColor;
            });
        },

        // 添加标题的通用方法
        addTitle(text, container, head = "h2") {
            const h2 = document.createElement(head);
            h2.textContent = text;
            container.append(h2);
        },

        // 添加题目
        subject(list) {
            const p = document.createElement("p");
            p.textContent = list[0]; // 题目内容
            p.className = "subject"; // 设置题目样式类
            container.append(p);

            // 添加题目附加信息（如果有）
            for (let i = 1; i < list.length; i++) {
                let pO = document.createElement("p");
                pO.textContent = list[i];
                container.append(pO);
            }
        },

        // 添加选项
        option(option, answer) {
            option.forEach(item => {
                let p = document.createElement("p");
                if (item == answer) {
                    // 正确答案样式
                    p.classList = "option correct_answer";
                    p.textContent = item.replace("(正确答案)", ""); // 移除标记
                } else {
                    // 普通选项样式
                    p.className = "option";
                    p.textContent = item;
                }
                container.append(p);
            })
        }
    };

    // 从API获取题库数据并渲染
    fetch('https://192.168.1.122/fastapi/static/ArtificialIntelligenceTrainerTheoryQuestionBank.2022.json')
        .then(response => response.json()) // 解析JSON响应
        .then(data => appendElement.main(data)) // 渲染数据
        .catch(error => console.error('错误:', error)); // 错误处理
</script>

</html>